import axios from 'axios'
import type { Weather, WeatherForecast, City, ApiResponse } from '@/types'
import { ElMessage } from 'element-plus'

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const apiKey = import.meta.env.VITE_WEATHER_API_KEY
    if (apiKey) {
      config.params = {
        ...config.params,
        key: apiKey
      }
    }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器
api.interceptors.response.use(
  response => response,
  error => {
    if (error.response) {
      const { status, data } = error.response
      switch (status) {
        case 401:
          ElMessage.error('API密钥无效')
          break
        case 404:
          ElMessage.error('城市未找到')
          break
        case 429:
          ElMessage.error('请求过于频繁，请稍后再试')
          break
        default:
          ElMessage.error(data?.message || '网络错误，请稍后再试')
      }
    }
    return Promise.reject(error)
  }
)

// 模拟数据（开发环境使用）
const getMockWeather = (city: string): Weather => {
  const conditions = ['晴', '多云', '阴', '小雨', '中雨', '大雨', '雪', '雾']
  const condition = conditions[Math.floor(Math.random() * conditions.length)]
  
  return {
    id: `mock-${Date.now()}`,
    city,
    temperature: Math.floor(Math.random() * 30) + 10,
    temperatureUnit: 'C',
    humidity: Math.floor(Math.random() * 60) + 40,
    windSpeed: Math.floor(Math.random() * 20) + 5,
    windDirection: 'NE',
    condition,
    conditionCode: '100',
    icon: '100',
    description: `${city}今天${condition}`,
    pressure: 1013,
    visibility: 10000,
    sunrise: '06:30',
    sunset: '18:30',
    timestamp: new Date().toISOString(),
    lastUpdated: new Date().toISOString()
  }
}

// API接口封装
export const weatherApi = {
  // 获取当前天气
  async getCurrentWeather(city: string): Promise<ApiResponse<Weather>> {
    try {
      if (import.meta.env.DEV && !import.meta.env.VITE_WEATHER_API_KEY) {
        return {
          success: true,
          data: getMockWeather(city)
        }
      }
      
      // 获取城市ID
      const locationResponse = await api.get('/geo/v2/city/lookup', {
        params: {
          location: city,
          lang: 'zh'
        }
      })
      
      if (locationResponse.data.code !== '200' || !locationResponse.data.location?.length) {
        throw new Error('城市未找到')
      }
      
      const locationId = locationResponse.data.location[0].id
      
      // 获取实时天气
      const response = await api.get('/v7/weather/now', {
        params: {
          location: locationId,
          lang: 'zh'
        }
      })
      
      const data = response.data
      if (data.code !== '200') {
        throw new Error(`API错误: ${data.code}`)
      }
      
      const now = data.now
      const weather: Weather = {
        id: `qweather-${Date.now()}`,
        city,
        temperature: parseInt(now.temp),
        temperatureUnit: 'C',
        humidity: parseInt(now.humidity),
        windSpeed: parseFloat(now.windSpeed),
        windDirection: now.windDir,
        condition: now.text,
        conditionCode: now.icon,
        icon: now.icon,
        description: now.text,
        pressure: parseInt(now.pressure),
        visibility: parseInt(now.vis),
        sunrise: '', // 需要额外API调用
        sunset: '', // 需要额外API调用
        timestamp: new Date().toISOString(),
        lastUpdated: now.obsTime
      }
      
      return {
        success: true,
        data: weather
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取天气失败'
      }
    }
  },
  
  // 获取天气预报
  async getWeatherForecast(city: string, days: 3 | 7 = 3): Promise<ApiResponse<WeatherForecast[]>> {
    try {
      if (import.meta.env.DEV && !import.meta.env.VITE_WEATHER_API_KEY) {
        const forecasts: WeatherForecast[] = []
        for (let i = 1; i <= days; i++) {
          const date = new Date()
          date.setDate(date.getDate() + i)
          
          forecasts.push({
            date: date.toISOString(),
            tempMin: Math.floor(Math.random() * 10) + 10,
            tempMax: Math.floor(Math.random() * 10) + 20,
            condition: '晴',
            icon: '100',
            humidity: Math.floor(Math.random() * 60) + 40,
            windSpeed: Math.floor(Math.random() * 20) + 5,
            precipitation: Math.random() * 10
          })
        }
        
        return {
          success: true,
          data: forecasts
        }
      }
      
      // 获取城市ID
      const locationResponse = await api.get('/geo/v2/city/lookup', {
        params: {
          location: city,
          lang: 'zh'
        }
      })
      
      if (locationResponse.data.code !== '200' || !locationResponse.data.location?.length) {
        throw new Error('城市未找到')
      }
      
      const locationId = locationResponse.data.location[0].id
      
      // 获取天气预报
      const response = await api.get(`/v7/weather/${days}d`, {
        params: {
          location: locationId,
          lang: 'zh'
        }
      })
      
      const data = response.data
      if (data.code !== '200') {
        throw new Error(`API错误: ${data.code}`)
      }
      
      // 转换为WeatherForecast格式
      const forecasts: WeatherForecast[] = data.daily.map((day: any) => ({
        date: day.fxDate,
        tempMin: parseInt(day.tempMin),
        tempMax: parseInt(day.tempMax),
        condition: day.textDay,
        icon: day.iconDay,
        humidity: parseInt(day.humidity),
        windSpeed: parseFloat(day.windSpeedDay),
        precipitation: parseFloat(day.precip) || 0
      }))
      
      return {
        success: true,
        data: forecasts
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取天气预报失败'
      }
    }
  },
  
  // 搜索城市
  async searchCities(query: string): Promise<ApiResponse<City[]>> {
    try {
      if (import.meta.env.DEV && !import.meta.env.VITE_WEATHER_API_KEY) {
        const mockCities: City[] = [
          { id: '101010100', name: '北京', country: 'CN', lat: 39.9042, lon: 116.4074, timezone: 'Asia/Shanghai' },
          { id: '101020100', name: '上海', country: 'CN', lat: 31.2304, lon: 121.4737, timezone: 'Asia/Shanghai' },
          { id: '101280101', name: '广州', country: 'CN', lat: 23.1291, lon: 113.2644, timezone: 'Asia/Shanghai' },
          { id: '101280601', name: '深圳', country: 'CN', lat: 22.5431, lon: 114.0579, timezone: 'Asia/Shanghai' },
          { id: '101270101', name: '成都', country: 'CN', lat: 30.5728, lon: 104.0668, timezone: 'Asia/Shanghai' }
        ]
        
        return {
          success: true,
          data: mockCities.filter(city => 
            city.name.toLowerCase().includes(query.toLowerCase())
          )
        }
      }
      
      const response = await api.get('/geo/v2/city/lookup', {
        params: {
          location: query,
          lang: 'zh'
        }
      })
      
      const data = response.data
      if (data.code !== '200') {
        throw new Error(`API错误: ${data.code}`)
      }
      
      const cities: City[] = data.location.map((item: any) => ({
        id: item.id,
        name: item.name,
        country: item.country,
        lat: parseFloat(item.lat),
        lon: parseFloat(item.lon),
        timezone: item.tz
      }))
      
      return {
        success: true,
        data: cities
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '搜索城市失败'
      }
    }
  },
  
  // 获取日出日落时间
  async getSunriseSunset(locationId: string): Promise<ApiResponse<{sunrise: string, sunset: string}>> {
    try {
      const response = await api.get('/v7/astronomy/sun', {
        params: {
          location: locationId,
          lang: 'zh'
        }
      })
      
      const data = response.data
      if (data.code !== '200') {
        throw new Error(`API错误: ${data.code}`)
      }
      
      return {
        success: true,
        data: {
          sunrise: data.sunrise,
          sunset: data.sunset
        }
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取日出日落时间失败'
      }
    }
  },
  
  // 获取空气质量
  async getAirQuality(locationId: string): Promise<ApiResponse<any>> {
    try {
      const response = await api.get('/v7/air/now', {
        params: {
          location: locationId,
          lang: 'zh'
        }
      })
      
      const data = response.data
      if (data.code !== '200') {
        throw new Error(`API错误: ${data.code}`)
      }
      
      return {
        success: true,
        data: data.now
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取空气质量失败'
      }
    }
  },
  
  // 获取天气指数
  async getWeatherIndices(locationId: string): Promise<ApiResponse<any[]>> {
    try {
      const response = await api.get('/v7/indices/1d', {
        params: {
          location: locationId,
          lang: 'zh',
          type: '1,2,3,5,8,9,13' // 穿衣指数,洗车指数,感冒指数,紫外线指数,运动指数,旅游指数,化妆指数
        }
      })
      
      const data = response.data
      if (data.code !== '200') {
        throw new Error(`API错误: ${data.code}`)
      }
      
      return {
        success: true,
        data: data.daily
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取天气指数失败'
      }
    }
  }
}

// 辅助函数：获取风向
function getWindDirection(degree: number): string {
  const directions = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']
  const index = Math.round(degree / 45) % 8
  return directions[index]
} 